package com.xiyuan.smartutils.client.http;

import com.xiyuan.smartutils.IoUtils;

import java.io.*;
import java.net.HttpURLConnection;


/**
 * HTTP/HTTPS 流客户端
 *
 * @version v1.0.0 @author lgz 2018-8-3 新建与整理
 */
public class HttpStream extends HttpClient {
    private ByteArrayOutputStream out;
    private ByteArrayOutputStream in;
    
    public HttpStream(String url, String method) {
        super(url, method);
        this.out = new ByteArrayOutputStream();
    }
    
    /********************************************************************************/
    // 输出到服务端
    /********************************************************************************/
    
    /**
     * 获取输出流
     */
    public OutputStream getOutputStream() {
        return out;
    }
    
    /**
     * 输出字节
     */
    public void write(int b) {
        out.write(b);
    }
    
    /**
     * 输出字节数组
     */
    public void write(byte[] b) {
        out.write(b, 0, b.length);
    }
    
    /**
     * 输出字节数组偏移量
     */
    public void write(byte[] b, int off, int len) {
        out.write(b, off, len);
    }
    
    /********************************************************************************/
    // 输入到客户端
    /********************************************************************************/
    
    /**
     * 重写获取HTTP结果
     */
    public HttpResult getResult() {
        return new HttpResult(responseStatus, responseText, in == null ? null : in.toByteArray());
    }
    
    /**
     * 获取输入流
     */
    public InputStream getInputStream() {
        return new ByteArrayInputStream(in.toByteArray());
    }
    
    /**
     * 获取字节数组
     */
    public byte[] getBytes() {
        return in.toByteArray();
    }
    
    /********************************************************************************/
    // 实现HTTP抽象方法
    
    /********************************************************************************/
    @Override
    protected boolean doPreRequestProperty() {
        setDoOutput(true);
        return true;
    }
    
    @Override
    protected void doWriteContent(HttpURLConnection conn) throws IOException {
        out.writeTo(conn.getOutputStream());
    }
    
    @Override
    protected void doReadContent(HttpURLConnection conn) throws IOException {
        if (responseStatus == _302_FOUND_.getCode()) {
            // 重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_.getCode()) {
            // 错误
            responseText = getResponseError(conn);
            return;
        }
        
        // 成功
        in = new ByteArrayOutputStream();
        try (InputStream input = conn.getInputStream()) {
            IoUtils.putBytes(input, in);
        }
        
        responseText = "调用成功";
    }
}
